package exercise.jslide.jslide.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class FileUtils {
    public static String getFileName(String path) {
        return path.substring(path.lastIndexOf(File.separator) + 1);
    }

    public static String getFileNameWithoutExtension(String path) {
        String fileName = getFileName(path);
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    public static String getFileExtension(String path) {
        return path.substring(path.lastIndexOf(".") + 1);
    }

    //创建临时目录
    public static File createTempDirectory(String fileName) {
        File tempDir = new File(System.getProperty("java.io.tmpdir") + File.separator + fileName);
        tempDir.mkdir();
        return tempDir;
    }

    //创建临时文件
    public static File createTempFile(String filePath, String fileName) {
        File tempFile = new File(filePath + File.separator + fileName);
        try {
            tempFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tempFile;
    }

    //打包成ZIP文件

    /**
     * 压缩文件或文件夹（包括所有子目录文件）
     *
     * @param sourceFile 源文件
     * @param saveFile 保存地址
     * @throws IOException 异常信息
     */
    public static void zipFileTree(File sourceFile, File saveFile) throws IOException {
        ZipOutputStream zipOutputStream = null;
        try {
            // 压缩输出流
            zipOutputStream = new ZipOutputStream(new FileOutputStream(saveFile));
            zip(sourceFile, zipOutputStream, "");
        } finally {
            if (null != zipOutputStream) {
                // 关闭流
                try {
                    zipOutputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


    /**
     * 递归压缩文件
     *
     * @param file 当前文件
     * @param zipOutputStream 压缩输出流
     * @param relativePath 相对路径
     * @throws IOException IO异常
     */
    private static void zip(File file, ZipOutputStream zipOutputStream, String relativePath)
            throws IOException {

        FileInputStream fileInputStream = null;
        try {
            if (file.isDirectory()) { // 当前为文件夹
                // 当前文件夹下的所有文件
                File[] list = file.listFiles();
                if (null != list) {
                    // 递归压缩每个文件
                    for (File f : list) {
                        zip(f, zipOutputStream, relativePath + (relativePath.length() == 0 ? "" : "/") + (file.getName().startsWith("JSlideTempPath")?"":file.getName()));
                    }
                }
            } else { // 压缩文件
                // 计算文件的相对路径
                String entryName = relativePath.length() == 0 ? file.getName() : relativePath + "/" + (file.getName().startsWith("JSlideTempPath")?"":file.getName());
                // 写入单个文件
                zipOutputStream.putNextEntry(new ZipEntry(entryName));
                fileInputStream = new FileInputStream(file);
                int readLen;
                byte[] buffer = new byte[1024];
                while ((readLen = fileInputStream.read(buffer)) != -1) {
                    zipOutputStream.write(buffer, 0, readLen);
                }
                zipOutputStream.closeEntry();
            }
        } finally {
            // 关闭流
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


    /**
     * 解压
     *
     * @param zipFilePath 带解压文件
     * @param desDirectory 解压到的目录
     * @throws Exception
     */
    public static void unzip(String zipFilePath, String desDirectory) throws Exception {

        File desDir = new File(desDirectory);
        if (!desDir.exists()) {
            boolean mkdirSuccess = desDir.mkdir();
            if (!mkdirSuccess) {
                throw new Exception("创建解压目标文件夹失败");
            }
        }
        // 读入流
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
        // 遍历每一个文件
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            if (zipEntry.isDirectory()) { // 文件夹
                String unzipFilePath = desDirectory + File.separator + zipEntry.getName();
                // 直接创建
                mkdir(new File(unzipFilePath));
            } else { // 文件
                String unzipFilePath = desDirectory + File.separator + zipEntry.getName();
                File file = new File(unzipFilePath);
                // 创建父目录
                mkdir(file.getParentFile());
                // 写出文件流
                BufferedOutputStream bufferedOutputStream =
                        new BufferedOutputStream(new FileOutputStream(unzipFilePath));
                byte[] bytes = new byte[1024];
                int readLen;
                while ((readLen = zipInputStream.read(bytes)) != -1) {
                    bufferedOutputStream.write(bytes, 0, readLen);
                }
                bufferedOutputStream.close();
            }
            zipInputStream.closeEntry();
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
    }

    // 如果父目录不存在则创建
    public static void mkdir(File file) {
        if (null == file || file.exists()) {
            return;
        }
        mkdir(file.getParentFile());
        file.mkdir();
    }
}
